/* eslint-disable */
<template>
	<div>
		<el-dialog class="newlyForm" :title="$t('components.assignRole.title')" :visible.sync="assignRoleVisible" width="80%" @close="closeAddRoledialog">
	        <el-form :rules="rules1"  :inline="false" :model="searchRoleForm" ref="searchRoleForm" label-width="110px">
				<el-row>
					<el-col :span="6">
						<el-form-item :label="$t('common.byUserName')+':'" >
							<el-input  v-model="searchRoleForm.byUserName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.empName')+':'" >
							<el-input  v-model="searchRoleForm.empName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.positionName')+':'"  >
							<el-input  v-model="searchRoleForm.positionName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.orgName')+':'" >
							<el-input  v-model="searchRoleForm.orgName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
	                    <el-form-item :label="$t('common.subsysName')+':'" prop="subSysCode">
							<el-select v-model="searchRoleForm.subSysCode" :placeholder="$t('common.selectPlaceholder')" clearable>
								<el-option v-for="(item,index) in subSystemNameOptions" :key="index" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form  :inline="false" :model="mhroleSearchForm" ref="mhroleSearchForm" label-width="110px" >
							<el-form-item :label="$t('common.roleName')+':'" prop="roleName">
								<el-input  v-model="mhroleSearchForm.roleName" :placeholder="$t('common.inputPlaceholder')"></el-input>
							</el-form-item>
						</el-form>
				    </el-col>
					<el-col :span="6" style="margin-left:25px;">
						<el-button type="primary" @click.native="searchAssignRole()" >{{$t('common.searchBtn')}}</el-button>
					    <el-button  @click.native="resetsearchRoleForm" >{{$t('common.resetBtn')}}</el-button>
					</el-col>
				</el-row>
			</el-form>
			<!-- 穿梭框部分 -->
			<el-row>
				<el-col :span="9">
					<p style="font-weight:bold;">{{$t('components.assignRole.canselectRoleList')}}</p>
	                <el-table class="data-list " max-height="500" v-loading="loadind" ref="canselectRoleList1" :data="canselectRoleList1" border @selection-change="changecanselectRoleList" highlight-current-row>
			            <el-table-column  type="selection" width="55" fixed="left" show-overflow-tooltip></el-table-column>
			            <el-table-column  prop="ruleType" :label="$t('common.ruleType')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="roleName" :label="$t('common.roleName')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="roleResources" :label="$t('common.isSpecial')"  show-overflow-tooltip></el-table-column>
		            </el-table>
				</el-col>
				<el-col :span="3">
					<div style="margin-bottom:10px;text-align:center;margin-top:80px;">
						<el-button type="primary" icon="el-icon-arrow-right" :disabled="!this.selectedcanselectRoleList.length" @click.native="addAssignRoleList">{{$t('common.add')}}</el-button>
					</div>
	                <div style="text-align:center;margin-top:25px;">
						<el-button  icon="el-icon-arrow-left"  type="danger"  :disabled="!this.selectedAssignRoleList.length" @click.native="removeAssignRoleList">{{$t('common.remove')}}</el-button>
					</div>
				</el-col>
				<el-col :span="12">
					<p style="font-weight:bold;">{{$t('components.assignRole.assignRoleList')}} <el-button  size="small" v-if="showDefaultRoleVisible" @click.native="setDefaultRole">{{$t('components.assignRole.setDefaultRole')}}</el-button> </p>
	                <el-table class="data-list"  max-height="500"  v-loading="loadind" ref="AssignRoleList1" :data="AssignRoleList1" border @selection-change="changecanAssignRoleList" highlight-current-row>
			            <el-table-column  type="selection" width="55" fixed="left" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="isDefaultRole" :label="$t('components.assignRole.isDefaultRole')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="ruleType" :label="$t('common.ruleType')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="roleName" :label="$t('common.roleName')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="roleResources" :label="$t('common.isSpecial')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="startTm"  :label="$t('common.startTm')" show-overflow-tooltip></el-table-column>
						<el-table-column  prop="endTm" :label="$t('common.endTm')" show-overflow-tooltip></el-table-column>
		            </el-table>
				</el-col>
			</el-row>
			<!-- 穿梭框部分 -->
			<div style="margin-top:15px;text-align:right;"><el-button  @click.native="closeAddRoledialog">{{$t('common.close')}}</el-button></div>
	    </el-dialog>
		<!-- 添加角色授权的弹窗 -->
		<validity-date path='noStart' :visible="addRoleValidityVisible"  :earliestTime="new Date().getTime()"  @validityDateClose="addRoleValidityClose" @submitDateForm="submitaddRoleValidity"></validity-date>
		<!-- 添加角色授权的弹窗 -->
	</div>
</template>

<script>
import validityDate from "./validityDate"
import {
    Message, Notification, MessageBox, Loading
} from 'element-ui'
export default {
    name: 'assignRole',
    props: [
        'visible', 'form'
    ],
    components: {
	       validityDate
    },
    data () {
        return {
            assignRoleVisible: false,
            showDefaultRoleVisible: false,
            searchRoleForm: {},
            mhroleSearchForm: {
	                roleName: ""
            },
            canselectRoleList: [],
            canselectRoleList1: [],
            AssignRoleList: [],
            AssignRoleList1: [],
            selectedcanselectRoleList: [],
            selectedAssignRoleList: [],
            subSystemNameOptions: [],
            rules1: {
                subSysCode: [
                    { required: true, message: this.$t('validateWornText.selectSubSysCode'), trigger: 'change' }
                ],
			        byUserName: [
                    { required: true, message: this.$t('validateWornText.inputByAccount'), trigger: 'change' }
			        ]
            },
            loadind: false,
            addRoleValidityVisible: false
        }
    },
    watch: {
        visible: 'visibleChange'
    },
    mounted () {
    },
    methods: {
        visibleChange (val) {
            this.assignRoleVisible = val
            if (val) {
                // 向后台发起请求请求子系统名称;
				   // 向后台发起请求请求子系统名称;
                this.getSubSystemList('')
                this.searchRoleForm = this.$deepCopy(this.form)
                this.searchBybyUserName()
                this.ifShowDefault()
            }
        },
        /**
			 * @author：xmj
			 * @function:获取子系统列表
			 */
        async getSubSystemList (val) {
            this.subSystemNameOptions = await this.$getSubSystemList(val)
        },
        searchAssignRole () {
            if (this.searchRoleForm.sysAccountStatus == 1 && this.searchRoleForm.sysUserName != "") {
                this.$refs['searchRoleForm'].validate((valid) => {
                    if (valid) {
                        // 如果验证通过向后台发起请求;
                        this.getCanSelectRoleList()
                        this.getAssignRoleList()
                    } else {
                        return false
                    }
				   })
            } else {
				    this.$message(this.$t('components.assignRole.assignRoleErrorTip'))
			    }
        },
        resetsearchRoleForm () {
            this.$refs["searchRoleForm"].resetFields()
            this.$refs["mhroleSearchForm"].resetFields()
        },
        // 根据百源账号名查询相关信息;
        searchBybyUserName () {
            // 为了避免在清空select选项的时候会触发on-change事件;
            if (this.searchRoleForm.byUserName.length > 0) {
                this.$httpExt().get('/dev-basp-user/userRole/queryUserInfo/' + this.searchRoleForm.byUserName)
                .then((response) => {
                    if (response.succ == "ok") {
                        this.searchRoleForm.sysUserName = response.result[0] ? response.result[0].sysUserName : ""
                        this.searchRoleForm.empName = response.result[0] ? response.result[0].empName : ""
                        this.searchRoleForm.positionName = response.result[0] ? response.result[0].positionName : ""
                        this.searchRoleForm.orgName = response.result[0] ? response.result[0].orgName : ""
                        this.searchRoleForm.byAccountId = response.result[0] ? response.result[0].byAccountId : ""
                        this.searchRoleForm.sysAccountStatus = response.result[0] ? response.result[0].sysAccountStatus : ""
                    }
                }, (response) => {
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
				  })
            }
        },
        getCanSelectRoleList () {
            let param = {
	                byAccountId: this.searchRoleForm.byAccountId,
                subSysCode: this.searchRoleForm.subSysCode
            }
            let that = this
		    this.$httpExt().post('/dev-basp-user/userRole/queryRoleList', param)
			    .then((response) => {
                if (response.succ == "ok") {
                    this.canselectRoleList = response.result.map(function (item, key, ary) {
                        for (let i in item) {
                            if (i == "isSpecial") {
                                if (item[i] == 1) {
                                    item[i] = that.$t('common.is')
                                } else {
                                    item[i] = that.$t('common.not')
                                }
                            }
                        }
                        return item
                    })
                    this.canselectRoleList1 = this.canselectRoleList
                    this.canselectRoleList1 = this.canselectRoleList.filter(item => (item.roleName.indexOf(this.mhroleSearchForm.roleName) !== -1))
                }
            }, (response) => {
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        getAssignRoleList () {
            let param = {
                byAccountId: this.searchRoleForm.byAccountId,
                subSysCode: this.searchRoleForm.subSysCode
            }
            let that = this
            this.$httpExt().post('/dev-basp-user/userRole/queryUserRoleAuthoredList', param)
            .then((response) => {
                if (response.succ == "ok") {
                    this.AssignRoleList = response.result.map(function (item, key, ary) {
                        for (let i in item) {
                            if (i == "isSpecial" || i == "isDefaultRole") {
                                if (item[i] == 1) {
                                    item[i] = that.$t('common.is')
                                } else {
                                    item[i] = that.$t('common.not')
                                }
                            } else if (i == "startTm" || i == "endTm") {
                                item[i] = that.$format(item[i], "yyyy/MM/dd hh:mm:ss")
                            }
                        }
                        return item
                    })
                    this.AssignRoleList1 = this.AssignRoleList
                    this.AssignRoleList1 = this.AssignRoleList.filter(item => (item.roleName.indexOf(this.mhroleSearchForm.roleName) !== -1))
                }
            }, (response) => {
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        changecanselectRoleList (value) {
            this.selectedcanselectRoleList = value
        },
        changecanAssignRoleList (value) {
            this.selectedAssignRoleList = value
        },
        // 查询系统是否可以切换角色,如果可以那么显示设为默认角色按钮;如果不可以那么不显示设为默认按钮;
        ifShowDefault () {
            this.$httpExt().get('/dev-basp-user/userRole/queryIsSwitchRole/1')
	            .then((response) => {
                if (response.succ == "ok") {
                    this.showDefaultRoleVisible = response.result
                }
            }, (response) => {
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        addAssignRoleList () {
	            this.addRoleValidityVisible = true
        },
        removeAssignRoleList () {
            let param = {
                idList: [],
                status: 0,
                systemId: 1
            }
            let that = this
            this.selectedAssignRoleList.map(function (item, key, ary) {
	                param.idList.push({ "byAccountId": that.searchRoleForm.byAccountId, "roleId": item.roleId, id: item.id })
            })
            this.$confirm(this.$t('components.assignRole.removeTip'), this.$t('common.tip'), {
                confirmButtonText: this.$t('common.submitOption'),
                cancelButtonText: this.$t('common.cancelOption'),
                type: 'warning'
            }).then(() => {
			    this.$httpExt().post('/dev-basp-user/userRole/state', param)
			    .then((response) => {
                    if (response.succ == "ok") {
                        this.$message({
                            type: 'success',
                            message: this.$t('components.assignRole.disabledSuccess')
                        })
                        this.getCanSelectRoleList()
                        this.getAssignRoleList()
                    }
                }, (response) => {
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
            }).catch(() => {
            })
        },
        dialogClose () {
            this.$refs["searchRoleForm"].resetFields()
            this.canselectRoleList1 = []
            this.AssignRoleList1 = []
        },
        closeAddRoledialog () {
            /* 去掉所有的判断条件关闭弹窗的时候 */
            /* 修改日期：2018-08-14,修改之前根据showDefaultRoleVisible；addDefault+=item.isDefaultRole;
				向后台发送请求，查看当前系统下是否已经有默认角色;三个条件来判断 */
            this.dialogClose()
            this.$emit('close')
        },
        addRoleValidityClose () {
	            this.addRoleValidityVisible = false
        },
        submitaddRoleValidity (dialogForm) {
            let urlH = '/dev-basp-user/userRole/add'
            let param = {
                endTm: dialogForm.endTm,
                startTm: dialogForm.startTm,
                isDefaultRole: 0,
				    idList: [],
                systemId: 1,
                status: 1
            }
            let that = this
	            this.selectedcanselectRoleList.map(function (item, key, ary) {
                param.idList.push({ "byAccountId": that.searchRoleForm.byAccountId, "roleId": item.roleId })
            })
            let loadingInstance = Loading.service({ fullscreen: true })
            this.$httpExt().post(urlH, param)
                .then((response) => {
                    this.addRoleValidityVisible = false
                    loadingInstance.close()
                    this.getCanSelectRoleList()
                    this.getAssignRoleList()
                    this.$emit('removeAssignRoleList')
                    Notification.success({
                        title: this.$t('components.assignRole.success'),
                        message: this.$t('components.assignRole.appendSuccess')
                    })
                }, (response) => {
                    loadingInstance.close()
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
        },
        setDefaultRole () { // 设置默认角色
            if (this.selectedAssignRoleList.length == 1) {
                let param = {
                    byAccountId: this.searchRoleForm.byAccountId,
                    isDefaultRole: 1,
                    roleId: this.selectedAssignRoleList[0].roleId,
                    systemId: 1,
                    id: this.selectedAssignRoleList[0].id
                }
	            this.$httpExt().post('/dev-basp-user/userRole/setDefaultRole', param)
	            .then((response) => {
                    if (response.succ == "ok") {
							  this.getAssignRoleList()
							  Notification.success({
								  title: this.$t('components.assignRole.success'),
								  message: this.$t('components.assignRole.setDefaultSuccess')
						      })
                    }
                }, (response) => {
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
                })
            } else {
                MessageBox({
                    message: this.$t('components.assignRole.singleSelectTip'),
                    confirmButtonText: this.$t('common.iknow')
                })
            }
        }
    }
}
</script>
<style lang="less">
 .newlyForm p{
    display: block;
    -webkit-margin-before: 1em;
    -webkit-margin-after: 1em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
}
</style>
